/*
 * hostinfo.cpp
 *
 *  Created on: Oct 8, 2012
 *      Author: mark
 */

#include "hostinfo.h"

/*
 * Get the local IP address.
 */
in_addr_t HostInfo::GetLocalIPAddress(const char *interface)
{
	struct ifaddrs *addressCollection, *address;
	int s;
	//char *host = (char*) malloc(NI_MAXHOST);
	char host[NI_MAXHOST];

	getifaddrs(&addressCollection);

	for (address = addressCollection; address != NULL; address = address->ifa_next)
	{
		s = getnameinfo(address->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

		if (s == 0) {
			if ((strcmp(address->ifa_name, interface) == 0) && (address->ifa_addr->sa_family == AF_INET))
			{
				//return host;
				return inet_addr(host);
			}
		}
	}
	return inet_addr("127.0.0.1");
}

/*
 * Convert an IP address to a char array.
 */
char *HostInfo::IPAddressToChar(const in_addr_t ipAddress)
{
	char *retval = (char*) malloc(INET_ADDRSTRLEN);
	inet_ntop(AF_INET, &ipAddress, retval, INET_ADDRSTRLEN);

	return retval;
}

in_addr_t HostInfo::CharToIPAddress(const char *ipAddress)
{
	return inet_addr(ipAddress);
}



























